<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/axios@1.6.7/dist/axios.min.js"></script>
    <script>
      // 拦截器
      axios.interceptors.request.use(
        function (config) {
          // Do something before request is sent
          console.log("请求拦截器");
          const token = localStorage.getItem("token");
          config.headers.Authorization = `Bearer ${token}`;
          return config;
        },
        function (error) {
          // Do something with request error
          return Promise.reject(error);
        }
      );

      // Add a response interceptor
      axios.interceptors.response.use(
        function (response) {
          console.log("响应拦截器");
          const { authorization } = response.headers;
          authorization && localStorage.setItem("token", authorization);

          // Any status code that lie within the range of 2xx cause this function to trigger
          // Do something with response data
          return response;
        },
        function (error) {
          // Any status codes that falls outside the range of 2xx cause this function to trigger
          // Do something with response error
          return Promise.reject(error);
        }
      );
    </script>
  </head>
  <body>
    <h1>登录页面</h1>
    <div>
      <div>用户名:<input id="username" /></div>
      <div>密码:<input type="password" id="password" /></div>
      <div><button id="login">登录</button></div>
    </div>

    <script>
      var username = document.querySelector("#username");
      var password = document.querySelector("#password");
      var login = document.querySelector("#login");

      login.onclick = () => {
        console.log(username.value, password.value);
        axios
          .post("/api/login", {
            username: username.value,
            password: password.value,
          })
          .then((res) => {
            console.log(res);
            if (res.data.ok === 1) {
              location.href = "/";
            }
          });
      };
    </script>
  </body>
</html>
